package com.zbfd.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.InMemoryRouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author: LCG
 * @date: 2022-10-26 19:28:15
 * @description: 动态路由的实现
 **/
@Component
public class DynamicRouterService implements ApplicationEventPublisherAware {

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    @Autowired
    private InMemoryRouteDefinitionRepository routeDefinitionRepository;

    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
         this.applicationEventPublisher=applicationEventPublisher;
    }



    public void addRoutes(RouteDefinition routeDefinition){
        //添加路由
        routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
        //刷新路由
        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
    }


    public void deleteRoutes(String id){
        //添加路由
        routeDefinitionWriter.delete(Mono.just(id)).subscribe();
        //刷新路由
        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
    }

    public Flux<RouteDefinition> getRoutes(){

        Flux<RouteDefinition> routeDefinitions = routeDefinitionRepository.getRouteDefinitions();

        return routeDefinitions;
    }

}
